﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LocalizedDisplayNameAttribute.cs" company="Spenta Consulting">
//   (c) Copyright 2011
// </copyright>
// <summary>
//   Extends the DisplayNameAttribute to provide a custom message
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Spenta.StreetCare.Core.Attributes
{
    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    using System.Resources;

    /// <summary>
    /// Extends the DisplayNameAttribute to provide a custom message
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedDisplayNameAttribute"/> class.
        /// </summary>
        /// <param name="resourceKey">The key in the resource file.</param>
        public LocalizedDisplayNameAttribute(string resourceKey)
            : base(LookupResource(resourceKey))
        {
        }

        /// <summary>
        /// Returns a text associated with a given key in the internal resource file.
        /// </summary>
        /// <param name="resourceKey">The resource key.</param>
        /// <returns>The text associated with the given key</returns>
        internal static string LookupResource(string resourceKey)
        {
            var resourceType = typeof(Silverlight.Resources.Spenta_StreetCare_Core);
            PropertyInfo property = resourceType.GetProperties().FirstOrDefault(p => p.PropertyType == typeof(ResourceManager));
            
            return property != null ? ((ResourceManager)property.GetValue(null, null)).GetString(resourceKey) : resourceKey;
        }
    }
}
